package com.cskaoyan.service.admin;

import com.cskaoyan.bean.PageDataVo;
import com.cskaoyan.bean.admin.Admin;
import com.cskaoyan.bean.admin.AdminExample;
import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.bean.admin.bo.PasswordBo;
import com.cskaoyan.exception.admin.AdminEmptyException;
import com.cskaoyan.exception.admin.PasswordErrorException;
import com.cskaoyan.mapper.admin.AdminMapper;
import com.cskaoyan.utils.StringUtils;
import com.github.pagehelper.PageHelper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 类<code>Doc</code>用于：TODO
 *
 * @author Acher
 * @version 1.0
 * @date 2021-10-18
 */
@Service
public class AdminServiceImpl implements AdminService{

    @Autowired
    AdminMapper adminMapper;

    @Override
    public PageDataVo query(Admin admin) {
        String username = admin.getUsername();
        //配置分页信息 → 在执行预编译过程，会帮你拼接分页的sql语句
        PageHelper.startPage(admin.getPage(), admin.getLimit());
        AdminExample example = new AdminExample();
        //构造条件 → List<Criterion> → and方法做的事情就是构造一个Criterion的对象添加到List里
        //如果username不为null，拼接条件 and username like '%songge%'
        AdminExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(username))
            criteria.andUsernameLike("%" + username + "%");
        criteria.andDeletedEqualTo(false);
        //设置排序
        example.setOrderByClause(admin.getSort() + " " + admin.getOrder());
        List<Admin> adminList = adminMapper.selectByExample(example);
        //分页插件 → 做分页
        //执行完查询之后，可以获得分页结果 → 用哪些数据取决于你的前端需要哪些数据
        //PageInfo中需要传入查询结果
        return PageDataVo.ok(adminList);
    }

    @Override
    public boolean create(Admin admin) {
        return adminMapper.insert(admin) == 1;
    }

    @Override
    public boolean update(Admin admin) {
        return adminMapper.updateByPrimaryKeySelective(admin) == 1;
    }

    @Override
    public boolean delete(Admin admin) {
        return adminMapper.deleteByPrimaryKey(admin.getId()) == 1;
    }

    @SneakyThrows
    @Override
    public boolean updatePasswordByUsername(Admin admin, PasswordBo passwordBo) {
        // 根据username查admin表获取密码进行比对
        AdminExample example = new AdminExample();
        example.createCriteria().andUsernameEqualTo(admin.getUsername());
        List<Admin> admins = adminMapper.selectByExample(example);
        if (admins == null)
            throw new AdminEmptyException("用户不存在");
        String password = admins.get(0).getPassword();
        if (!password.equals(passwordBo.getOldPassword()))
            throw new PasswordErrorException("密码错误");
        admin.setPassword(passwordBo.getNewPassword());
        return adminMapper.updateByPrimaryKeySelective(admin) == 1;
    }
}
